import { createSketion, SketionHttp } from "sketion-http";
import { Notify, Toast } from "vant";
import { MyRequest, MyResponse } from "@/type";
import axios, { AxiosInstance, AxiosResponse } from "axios";

const baseUrl = process.env.VUE_APP_BASE_URL;

console.log("--baseUrl--", baseUrl);

export let sketionUtil: SketionHttp<MyRequest, MyResponse>;

let myAxios: AxiosInstance;

const msgMap: Record<number, string> = {
  400: "请求错误",
  401: "未授权，请重新登录",
  403: "拒绝访问",
  404: "请求出错",
  408: "请求超时",
  500: "服务器错误",
  501: "服务未实现",
  502: "网络错误",
  503: "服务不可用",
  504: "网络超时",
  505: "HTTP版本不受支持",
};

// 根据不同的状态码，生成不同的提示信息
const showStatus = (status: number) => {
  const msg = msgMap[status] || "未知错误";
  return `${msg}(${status})，请检查网络或联系管理员！`;
};

export function initHttp() {
  console.log("==initHttp==");
  myAxios = axios.create({
    baseURL: baseUrl,
    timeout: 2000,
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    transformRequest: [
      function (data) {
        return data;
      },
    ],
    timeoutErrorMessage: "请求超时(10s)，请检查网络或联系管理员",
    validateStatus: function (status) {
      return status < 600; // Reject only if the status code is greater than or equal to 500
    },
  });

  // 响应拦截器
  myAxios.interceptors.response.use(
    (response) => {
      const status = response.status;
      if (status < 200 || status >= 300) {
        // 处理http错误，抛到业务代码
        const msg = showStatus(status);
        const error = new Error(msg);
        if (status === 401) {
         // 退出登录
        }
        return Promise.reject(error);
      }
      return Promise.resolve(response);
    },
    (error: AxiosError) => {
      if (error.message === "Network Error") {
        error.message = "无可用网络或服务器异常，请检查网络或联系管理员！";
      }
      return Promise.reject(error);
    }
  );

  sketionUtil = createSketion({
    showLoading: (request) => {
      let text = "加载中...";
      if (request && request.loadingText) {
        text = request.loadingText;
      }
      Toast.loading({
        message: text,
        forbidClick: true,
        duration: 0,
      });
    },
    showWarn(res) {
      Notify({ type: "warning", message: res.msg });
    },
    showError(e) {
      console.dir(e);
      Notify({ type: "danger", message: e.message });
    },
    closeLoading() {
      Toast.clear();
    },
    sendRequest(request) {
      return myAxios(request as MyRequest);
    },
    parseRes(res: any) {
      const axiosRes = res as AxiosResponse;
      if (axiosRes.status === 200) {
        if (axiosRes.data) {
          return Promise.resolve(
            new MyResponse(
              axiosRes.data.code,
              axiosRes.data.msg,
              axiosRes.data.data,
              axiosRes
            )
          );
        } else {
          return new MyResponse(500, "res.data is null", null, axiosRes);
        }
      } else {
        return new MyResponse(res.status, res.statusText, null, axiosRes);
      }
    },
    parseError(error: Error) {
      return new MyResponse(500, error.message, null, error);
    },
    requestIsSuccess(res): boolean {
      return res.success;
    },
  });
}

export function sendRequest<T = any>(
  request: MyRequest
): Promise<MyResponse<T>> {
  return sketionUtil.sendRequest(request);
}

export function setAxiosHeader(key: string, value: string) {
  axios.defaults.headers.common[key] = value;
}
